const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { google } = require('googleapis');

// 1. 加载 OAuth2 客户端
const CLIENT_ID = '910115210799-n5bretrsk9dhrriscijlglu16aiucaok.apps.googleusercontent.com';
const CLIENT_SECRET = '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';
const REDIRECT_URI = `http://n8n.xjwjsw58.cfd/api/callback`;
const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);

// 2. 读取保存的 token
const TOKEN_PATH = path.join(__dirname, 'gmail-token.json');
if (fs.existsSync(TOKEN_PATH)) {
    oAuth2Client.setCredentials(JSON.parse(fs.readFileSync(TOKEN_PATH)));
}

async function checkAuth () {
    if (!oAuth2Client.credentials || !oAuth2Client.credentials.access_token) {
        const authUrl = await oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            prompt: "consent",
            scope: [
                'https://www.googleapis.com/auth/gmail.readonly',
                'https://www.googleapis.com/auth/gmail.send',
            ],
        });
        console.log(authUrl);
        const url = `https://api.telegram.org/bot7647150566:AAETC-HaxsM9ZsVHfy4tMmg9hK2bZwFb17c/sendMessage`;
        const response = await axios.get(url, {
            params: {
                chat_id: '5908447022',
                text: authUrl
            }
        });
        console.log(response.data);
        return {
            msg: authUrl,
            code: 300
        }
    } else {
        return {
            msg: '已经授权，可以调用 Gmail API',
            code: 200
        }
    }
}

async function oauth2callback (code) {
    const { tokens } = await oAuth2Client.getToken(code);

    oAuth2Client.setCredentials(tokens);
    fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokens, null, 2));
    return {
        msg: '授权成功，可以关闭页面',
        code: 200
    }
}

async function sendMail (subject, content) {
    function createMessage (from, to, subject, body) {
        const encodedSubject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
        const message = [
            `From: ${from}`,
            `To: ${to}`,
            `Subject: ${encodedSubject}`,
            'MIME-Version: 1.0',
            'Content-Type: text/plain; charset="UTF-8"',
            'Content-Transfer-Encoding: 7bit',
            '',
            body,
        ].join('\n');

        return Buffer.from(message)
            .toString('base64')
            .replace(/\+/g, '-')
            .replace(/\//g, '_')
            .replace(/=+$/, '');
    }
    const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
    const raw = createMessage('xiujun58abc@gmail.com', 'xiujun58abc@gmail.com', subject, content);
    await gmail.users.messages.send({
        userId: 'me',
        requestBody: { raw },
    });
    return {
        msg: '邮件发送成功',
        code: 200
    }
}

module.exports = {
    checkAuth,
    oauth2callback,
    sendMail
}

